package com.thread.exe;

import java.io.IOException;
import java.math.BigInteger;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CachedFactorizer extends GenericServlet{

	private static final long serialVersionUID = 1L;
	private BigInteger lastNumber;
	private BigInteger[] lastFactors;
	private long hits;
	private long cacheHits;
	
	public synchronized long getHits() {
		return hits;
	}
	
	public synchronized double getCacheHitRatio() {
		return (double) cacheHits / hits;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		BigInteger i = getParam(req);
		BigInteger[] factors = null;
		synchronized (this) {
			hits++;
			if(i.equals(lastNumber)) {
				cacheHits++;
				factors = lastFactors.clone();	//这里的防止factors再返回前被其他线程改变。
			}
		}
		
		if(factors == null) {
			factors = factor(i); //耗时很长
			synchronized (this) {
				lastNumber = i;
				lastFactors = factors.clone(); //这里的clone应该是防止引用泄漏
			}
		}
	}

	private BigInteger[] factor(BigInteger i) {
		return null;
	}

	private BigInteger getParam(ServletRequest req) {
		return null;
	}

}
